#!/usr/bin/perl -w
#
# reclaim:
#
# 2008, by Chris Mear -- based on original scripts gpsearch and optoutletter by Chris Lightfoot

my $rcsid = ''; $rcsid .= '$Id: reclaim.cgi 95 2009-04-27 10:56:49Z amlnmcgreggor $';

use strict;

require 5.8.0;

use CGI::Fast;
use HTML::Entities;
use IO::File;
use Text::CSV_XS;
use Cwd;
use Encode;
use File::Slurp;
use utf8;


my @forces;
my @names;
my @addresses;
my $C = new Text::CSV_XS();
my $h = new IO::File("policeforces.csv");
my $i = 0;
while (defined(my $line = $h->getline())) {
    chomp($line);
    $line =~ s/[^\00-\x7f]//g;
    $C->parse($line);
    my @f = $C->fields();
    push @forces, $f[0];
    push @names, $f[1];
    push @addresses, $f[2];
}

my %labels;
my @values;
for $i ( 0 .. $#forces ) {
  $labels{$i} = $forces[$i];
  $values[$i] = $i;
}

use charnames qw(:full);

sub page_head ($$) {
    my CGI::Fast $q = shift;
    my $title = shift;
    
    return <<EOF;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<link rel="stylesheet" href="/wp-content/themes/reclaimyourdna/style.css" media="screen"/>
<title>Reclaim Your DNA</title>
</head>

<body>
<div id="wrap">

    <div id="top" onclick="location.href='/';" style="cursor: pointer;">
    <a href="/">
        <img alt="Reclaim your DNA from Britain's National DNA Database" 
         src="/wp-content/themes/reclaimyourdna/img/logo.gif" id="logo" />
    </a>
         <h1 class="hidden"><a href="/">Reclaim Your DNA</a></h1>
    </div>

    <div id="content" class="form left">
EOF
}

sub page_foot ($) {
    my CGI::Fast $q = shift;
    return <<EOF;

    </div>
    
    <div id="sidebar" class="right">
    	<div class="pagenav">
            <ul>
                <li class="current_page_item"><a href="/">Home</a></li>

                <li id="write-your-letter" class="page_item page-item-17">
                    <a href="/help-with-your-letter/" 
                    title="Write your letter">Help with your letter</a></li>
                    
                <li id="innocent-people-on-the-dna-database" class="page_item page-item-181">
                	<a title="Innocent people on the DNA database" href="/innocent-people-on-the-dna-database/">Innocent people on the DNA database</a></li>
                
                <li id="what-happens-next" class="page_item page-item-185">
                <a title="What happens next?" href="/what-happens-next/">What happens next?</a></li>
                    
                <li id="contact-your-mp" class="page_item page-item-19">
                    <a href="/contact-your-mp/" 
                        title="Contact your MP">Contact your MP</a></li>

                <li id="further-action" class="page_item page-item-97">
                    <a href="/further-action/" 
                        title="Further action">Further action</a></li>

                <li id="further-information" class="page_item page-item-70">
                    <a href="/further-information/" 
                        title="Further information">Further information</a>
                    <ul>
                    	<li id="further-information_racial-bias" class="page_item page-item-316">
                    		<a title="Racial bias" href="/further-information/racial-bias/">Racial bias</a></li>
                        <li id="further-information_what-happens-to-my-dna" class="page_item page-item-7">
                            <a href="/further-information/what-happens-to-my-dna/" 
                            title="What happens to my DNA?">What happens to my DNA?</a></li>
                        <li id="further-information_what-are-the-issues" class="page_item page-item-15">
                            <a href="/further-information/what-are-the-issues/" 
                            title="What are the issues?">What are the issues?</a></li>
                        <li id="further-information_ten-myths-about-the-national-dna-database" 
                            class="page_item page-item-16">
                            <a href="/further-information/ten-myths-about-the-national-dna-database/" 
                            title="Ten myths about the National DNA Database">Ten myths about the 
                            National DNA Database</a></li>
                    </ul>
                </li>

                <li id="about-us" class="page_item page-item-111">
                    <a href="/about-us/" title="About us">About us</a></li>
            </ul>
        </div>

        <ul class="linkedlist">
            <li>
            </li>
        </ul>

        <ul class="linkedlist">
        <li><h2 class="reclaimlink"><a href="/reclaim">Write your letter &raquo;</a>
        </h2></li>
        </ul>

        <ul class="outerlinkedlist">
            <li class="categories"><h2>Categories</h2>
                <ul>
                    <li class="cat-item cat-item-8"><a href="/category/news/" 
                        title="Further action you can take about the DNA database 
                        will be added here.">Further action</a></li>

                    <li class="cat-item cat-item-6"><a href="/category/further-information/" 
                        title="New sources of information about the DNA database 
                        will be added here.">News</a>
                    </li>
                
                    <li class="cat-item cat-item-3"><a href="/category/removal-procedure/" 
                        title="We will let you know here if there are any changes to the procedure for 
                        getting your DNA destroyed or your records removed.">Removal Procedure</a>
                    </li>
                </ul>
            </li>
        </ul>
        
        <ul class="linkedlist rsslinks">
      <li><h2>RSS/Updates by Email</h2></li>
        <li><p class="rss"<a href="http://feeds2.feedburner.com/ReclaimYourDna">RSS</a></p></li>
        <li><p class="rss"><a href="http://feedburner.google.com/fb/a/mailverify?uri=ReclaimYourDna">Blog updates by email</a></p></li>
      </ul>

    <ul class="linkedlist">
        <li><a href="/wp-login.php">Log-in</a></li>
    </ul>            

    </div>

    <div id="footer">
    </div>

</div>

</body>
</html>
EOF
}

# named unicode char to LaTeX incantation
my %unicode_tex_map = (
        'EM DASH' => '---',
        'EN DASH' => '--',

        'LEFT SINGLE QUOTATION MARK' => '`',
        'RIGHT SINGLE QUOTATION MARK' => "'",

        'LEFT DOUBLE QUOTATION MARK' => "``",
        'RIGHT DOUBLE QUOTATION MARK' => "''",
        
        'LATIN CAPITAL LETTER A WITH GRAVE' => '\\`{A}',
        'LATIN CAPITAL LETTER A WITH ACUTE' => '\\\'{A}',
        'LATIN CAPITAL LETTER A WITH CIRCUMFLEX' => '\\^{A}',
        'LATIN CAPITAL LETTER A WITH TILDE' => '\\~{A}',
        'LATIN CAPITAL LETTER A WITH DIAERESIS' => '\\"{A}',
        'LATIN CAPITAL LETTER A WITH RING ABOVE' => '\\AA',
        'LATIN CAPITAL LETTER AE' => '\\AE',
        'LATIN CAPITAL LETTER C WITH CEDILLA' => '\\c{C}',
        'LATIN CAPITAL LETTER E WITH GRAVE' => '\\`{E}',
        'LATIN CAPITAL LETTER E WITH ACUTE' => '\\\'{E}',
        'LATIN CAPITAL LETTER E WITH CIRCUMFLEX' => '\\^{E}',
        'LATIN CAPITAL LETTER E WITH DIAERESIS' => '\\"{E}',
        'LATIN CAPITAL LETTER I WITH GRAVE' => '\\`{I}',
        'LATIN CAPITAL LETTER I WITH ACUTE' => '\\\'{I}',
        'LATIN CAPITAL LETTER I WITH CIRCUMFLEX' => '\\^{I}',
        'LATIN CAPITAL LETTER I WITH DIAERESIS' => '\\"{I}',
        'LATIN CAPITAL LETTER N WITH TILDE' => '\\~{N}',
        'LATIN CAPITAL LETTER O WITH GRAVE' => '\\`{O}',
        'LATIN CAPITAL LETTER O WITH ACUTE' => '\\\'{O}',
        'LATIN CAPITAL LETTER O WITH CIRCUMFLEX' => '\\^{O}',
        'LATIN CAPITAL LETTER O WITH TILDE' => '\\~{O}',
        'LATIN CAPITAL LETTER O WITH DIAERESIS' => '\\"{O}',
        'LATIN CAPITAL LETTER O WITH STROKE' => '\\O',
        'LATIN CAPITAL LETTER U WITH GRAVE' => '\\`{U}',
        'LATIN CAPITAL LETTER U WITH ACUTE' => '\\\'{U}',
        'LATIN CAPITAL LETTER U WITH CIRCUMFLEX' => '\\^{U}',
        'LATIN CAPITAL LETTER U WITH DIAERESIS' => '\\"{U}',
        'LATIN CAPITAL LETTER Y WITH ACUTE' => '\\\'{Y}',
        'LATIN SMALL LETTER SHARP S' => '\\sz',
        
        'LATIN SMALL LETTER A WITH GRAVE' => '\\`{a}',
        'LATIN SMALL LETTER A WITH ACUTE' => '\\\'{a}',
        'LATIN SMALL LETTER A WITH CIRCUMFLEX' => '\\^{a}',
        'LATIN SMALL LETTER A WITH TILDE' => '\\~{a}',
        'LATIN SMALL LETTER A WITH DIAERESIS' => '\\"{a}',
        'LATIN SMALL LETTER A WITH RING ABOVE' => '\\aa',
        'LATIN SMALL LETTER AE' => '\\ae',
        'LATIN SMALL LETTER C WITH CEDILLA' => '\\c{c}',
        'LATIN SMALL LETTER E WITH GRAVE' => '\\`{e}',
        'LATIN SMALL LETTER E WITH ACUTE' => '\\\'{e}',
        'LATIN SMALL LETTER E WITH CIRCUMFLEX' => '\\^{e}',
        'LATIN SMALL LETTER E WITH DIAERESIS' => '\\"{e}',
        'LATIN SMALL LETTER I WITH GRAVE' => '\\`{i}',
        'LATIN SMALL LETTER I WITH ACUTE' => '\\\'{i}',
        'LATIN SMALL LETTER I WITH CIRCUMFLEX' => '\\^{\i}',
        'LATIN SMALL LETTER I WITH DIAERESIS' => '\\"{\i}',
        'LATIN SMALL LETTER N WITH TILDE' => '\\~{n}',
        'LATIN SMALL LETTER O WITH GRAVE' => '\\`{o}',
        'LATIN SMALL LETTER O WITH ACUTE' => '\\\'{o}',
        'LATIN SMALL LETTER O WITH CIRCUMFLEX' => '\\^{o}',
        'LATIN SMALL LETTER O WITH TILDE' => '\\~{o}',
        'LATIN SMALL LETTER O WITH DIAERESIS' => '\\"{o}',
        'LATIN SMALL LETTER O WITH STROKE' => '\\o',
        'LATIN SMALL LETTER U WITH GRAVE' => '\\`{u}',
        'LATIN SMALL LETTER U WITH ACUTE' => '\\\'{u}',
        'LATIN SMALL LETTER U WITH CIRCUMFLEX' => '\\^{u}',
        'LATIN SMALL LETTER U WITH DIAERESIS' => '\\"{u}',
        'LATIN SMALL LETTER Y WITH ACUTE' => '\\\'{y}'
    );

my $sub = 'sub tex_map ($) { if '
            . join ("\n} elsif ",
                map { sprintf('($_[0] =~ /^\N{%s}$/) { return $unicode_tex_map{"%s"}; ',
                                $_, $_) } keys(%unicode_tex_map))
            . '} else { return undef; } }';
#print "$sub\n";
#eval($sub) or die $@;

# for some reason the generated code above didn't work, so include the output
sub tex_map ($) {
    if ($_[0] =~ /^\N{LATIN CAPITAL LETTER U WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER U WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER A WITH TILDE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER A WITH TILDE"}; 
    } elsif ($_[0] =~ /^\N{RIGHT DOUBLE QUOTATION MARK}$/) {
        return $unicode_tex_map{"RIGHT DOUBLE QUOTATION MARK"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER I WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER I WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER N WITH TILDE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER N WITH TILDE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER Y WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER Y WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER E WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER E WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER O WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER O WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER E WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER E WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{RIGHT SINGLE QUOTATION MARK}$/) {
        return $unicode_tex_map{"RIGHT SINGLE QUOTATION MARK"}; 
    } elsif ($_[0] =~ /^\N{LEFT SINGLE QUOTATION MARK}$/) {
        return $unicode_tex_map{"LEFT SINGLE QUOTATION MARK"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER E WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER E WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER O WITH STROKE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER O WITH STROKE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER O WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER O WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER U WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER U WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER A WITH RING ABOVE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER A WITH RING ABOVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER I WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER I WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER O WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER O WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER E WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER E WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER O WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER O WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER A WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER A WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER A WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER A WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER O WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER O WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER O WITH TILDE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER O WITH TILDE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER A WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER A WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER C WITH CEDILLA}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER C WITH CEDILLA"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER U WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER U WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER E WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER E WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER U WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER U WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER I WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER I WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER O WITH TILDE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER O WITH TILDE"}; 
    } elsif ($_[0] =~ /^\N{EN DASH}$/) {
        return $unicode_tex_map{"EN DASH"}; 
    } elsif ($_[0] =~ /^\N{EM DASH}$/) {
        return $unicode_tex_map{"EM DASH"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER AE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER AE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER E WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER E WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER O WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER O WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER O WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER O WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER U WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER U WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER I WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER I WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER U WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER U WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER I WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER I WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER U WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER U WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER N WITH TILDE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER N WITH TILDE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER A WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER A WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER I WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER I WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER C WITH CEDILLA}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER C WITH CEDILLA"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER O WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER O WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER A WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER A WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER AE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER AE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER Y WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER Y WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER O WITH STROKE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER O WITH STROKE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER E WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER E WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER I WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER I WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER A WITH ACUTE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER A WITH ACUTE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER SHARP S}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER SHARP S"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER E WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER E WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LEFT DOUBLE QUOTATION MARK}$/) {
        return $unicode_tex_map{"LEFT DOUBLE QUOTATION MARK"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER I WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER I WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER U WITH CIRCUMFLEX}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER U WITH CIRCUMFLEX"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER A WITH DIAERESIS}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER A WITH DIAERESIS"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER A WITH RING ABOVE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER A WITH RING ABOVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN CAPITAL LETTER A WITH GRAVE}$/) {
        return $unicode_tex_map{"LATIN CAPITAL LETTER A WITH GRAVE"}; 
    } elsif ($_[0] =~ /^\N{LATIN SMALL LETTER A WITH TILDE}$/) {
        return $unicode_tex_map{"LATIN SMALL LETTER A WITH TILDE"};
    } else {
        return undef;
    }
}
    

sub to_tex ($;$) {
    my $text = shift;
    my $multiline = shift;

    # aargh. TeX is horrible.
    my $tex = '';
    my $last_was_space = 1;
    for (my $i = 0; $i < length($text); ++$i) {
        $last_was_space = ($i > 0);
        my $c = substr($text, $i, 1);
        if ($c eq "\n") {
            $tex .= (" \\\\\n");
            $last_was_space = 1;
        } elsif ($c =~ /^\s$/) {
            $tex .= ' ';
            $last_was_space = 1;
        } elsif ($c eq '\\') {
            $tex .= '$\backslash$';
        } elsif ($c eq '~') {
            $tex .= '\verb1~1';
        } elsif ($c eq '^') {
            $tex .= '\verb1^1';
        } elsif ($c =~ /^[#\$%&_{}]$/) {
            $tex .= "\\$c";
        } else {
            if (defined(my $d = tex_map($c))) {
                $tex .= $d;
            } elsif ($c eq "'") {
                if ($last_was_space) {
                    $tex .= "`";
                } else {
                    $tex .= "'";
                }
            } elsif ($c eq '"') {
                if ($last_was_space) {
                    $tex .= "``";
                } else {
                    $tex .= "''";
                }
            } elsif ($c =~ /^[A-Za-z0-9-]$/) {
                $tex .= $c;
            } else {
                # punt -- no idea what this is
                $tex .= ' ';
            }
        }
    }

    if ($tex =~ /xx/) {
        $tex =~ s/xx/{x}{x}/g;
    }

    return $tex;
}

my $letter_template_text = read_file("reclaim.tex");

sub make_letter ($$$$$$$$$) {
    my CGI::Fast $q = shift;
    my ($person_name, $person_addr, $cc_force, $cc_name, $cc_addr, $offence_date, $offence, $disposal) = @_;
    
    my $tex = $letter_template_text;
    
    $cc_addr =~ s/\\\\/\n/g;
    
    $offence = lcfirst($offence);

    $tex =~ s/xxPERSONNAME/to_tex($person_name)/eg;
    $tex =~ s/xxPERSONADDR/to_tex($person_addr, 1)/eg;
    $tex =~ s/xxCCFORCE/to_tex($cc_force)/eg;
    $tex =~ s/xxCCNAME/to_tex($cc_name)/eg;
    $tex =~ s/xxCCADDR/to_tex($cc_addr)/eg;
    $tex =~ s/xxDATE/to_tex($offence_date)/eg;
    $tex =~ s/xxOFFENCE/to_tex($offence)/eg;
    $tex =~ s/xxDISPOSAL/to_tex($disposal)/eg;

    my $tempdir;
    do {
        $tempdir = sprintf('/tmp/reclaim.%08x.%08x.%d', time(), int(rand(0xffffffff)), $$);
    } while (!mkdir($tempdir, 0700));

    my $olddir = getcwd();
    chdir($tempdir);

    write_file('letter.tex', $tex);
    `pdflatex letter.tex`;
    if (-e 'letter.pdf') {
        my $pdf = read_file('letter.pdf');

        system("rm", "-rf", $tempdir);

        print $q->header(
                    -type => 'application/pdf',
                    -content_length => length($pdf),
                    -content_disposition => 'attachment; filename=letter.pdf'
                ), $pdf;
    } else {
        warn "unable to create letter; tempdir = $tempdir\n";
        print $q->header(
                    -type => 'text/plain',
                    -status => '500 Script error'
                ),
                "Sorry -- we weren't able to create your letter. Please use the back button in your browser and try downloading a version to write your details onto yourself. Apologies for the inconvenience.";
    }
    chdir($olddir);
}

sub sanitise ($) {
    my $t_input = shift;
    return undef unless (defined($t_input));

    my $t;

    # now we might have either UTF-8 or ISO-8859-1
    my $f = 0;
    eval {
        $t = decode_utf8($t_input, Encode::FB_CROAK);
        $f = 1;
    };

    if (!$f) {
        $t = decode('cp1252', $t_input, Encode::FB_DEFAULT);
    }
    
    $t =~ s/^\s+//;
    $t =~ s/\s+$//;
    $t =~ s/(\r\n|\n\r)/\n/;
    $t =~ s/\n+$//;
    if ($t eq '') {
        return undef;
    } else {
        return $t;
    }
}


while (my $q = new CGI::Fast()) {
  my $cc_force_id = sanitise($q->param('cc_force_id'));
  my $person_name = sanitise($q->param('person_name'));
  my $person_addr = sanitise($q->param('person_addr'));
  my $offence_date = sanitise($q->param('offence_date'));
  my $offence = sanitise($q->param('offence'));
  my $disposal = sanitise($q->param('disposal'));

  if ($cc_force_id) {
    my $cc_force = $forces[$cc_force_id];
    my $cc_addr = $addresses[$cc_force_id];
    my $cc_name = $names[$cc_force_id];
    
    if (defined($person_name) && defined($person_addr)
        && defined ($cc_force) && defined($cc_name) && defined($cc_addr)) {
        make_letter($q, $person_name, $person_addr, $cc_force, $cc_name, $cc_addr, $offence_date, $offence, $disposal);
        next;
    }
  } else {
    print $q->header(),
            page_head($q, "Reclaim Your DNA"),
            $q->h1('Reclaim <em>your</em> DNA'),
            $q->p('Use this form to create a personalized letter for printing, signing, and posting to the appropriate Chief Constable to request that your details be removed from the National DNA Database.'),
            $q->p('Please use this form to generate a letter <strong>only</strong> if your DNA was taken on arrest in England, Wales, or Northern Ireland, and if you have <strong>never</strong> received a caution or conviction for <em>any</em> offence.'),
            $q->start_form(-method => 'POST'),
            $q->h3("Add your details:"),
            $q->p('The details you enter are used only to produce your letter. They will not be stored or otherwise be used by this website.'),
            $q->p($q->label("Your name"),
            $q->textfield(-name => 'person_name', -size => 32)
            ),
            $q->p($q->label("Your address"),
            $q->textarea(
                        -name => 'person_addr',
                        -columns => 32, -rows => 5)
            ),
            $q->p($q->label("Choose the police force from the list below:"),
            $q->p($q->popup_menu(-name => 'cc_force_id', -values => \@values, -labels => \%labels))),
            $q->p($q->label("The alleged offence you were arrested for:"),
            $q->textfield(-name => 'offence', -size => 32)
            ),
            $q->p($q->label("The date of the arrest:"),
            $q->textfield(-name => 'offence_date', -size => 32)
            ),
            $q->p($q->label("The disposal:"),
            $q->p($q->popup_menu(-name => 'disposal', -values => ['No further action was taken', 'The charges were dropped', 'I was acquitted']))
            ),
            $q->p('Click \'Go\' to see your customized letter. You should print and sign one copy for posting to the Chief Constable. You may wish to print another copy for sending to your MP, and a third for yourself.'),
            $q->p($q->submit(-value => 'Go')),
            $q->end_form(),
            page_foot($q);
  }
  

}
